package com.team.merchant.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.team.merchant.domain.vo.StatsMessage;
import com.team.merchant.websocket.MerchantWebSocketHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
public class WebSocketService {
    
    private final SimpMessagingTemplate messagingTemplate;
    private final ObjectMapper objectMapper;
    private final MerchantWebSocketHandler merchantWebSocketHandler;
    
    private static final String STATS_TOPIC = "/topic/stats";
    private static final String MINI_PROGRAM_TOPIC = "/topic/mini";
    
    /**
     * 发送统计数据到WebSocket客户端
     * @param statsMessage 统计数据消息
     */
    public void sendStatsUpdate(StatsMessage statsMessage) {
        try {
            log.info("准备发送WebSocket消息到主题: {}", STATS_TOPIC);
            log.info("消息内容: {}", statsMessage);
            
            // 发送消息到普通客户端
            messagingTemplate.convertAndSend(STATS_TOPIC, statsMessage);
            
            // 发送消息到微信小程序客户端（使用简化格式）
            sendToMiniProgram(statsMessage);
            
            // 通过MerchantWebSocketHandler广播消息
            merchantWebSocketHandler.broadcastStats(statsMessage);
            
            log.info("WebSocket消息发送成功");
        } catch (Exception e) {
            log.error("WebSocket消息发送失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 发送消息到微信小程序客户端
     * 微信小程序处理JSON格式可能有限制，使用简化格式
     */
    private void sendToMiniProgram(StatsMessage statsMessage) {
        try {
            // 创建简化版消息，适合小程序处理
            MiniProgramMessage miniMessage = new MiniProgramMessage();
            miniMessage.setType("stats");
            miniMessage.setTotalOrders(statsMessage.getTotalOrders());
            miniMessage.setTotalRevenue(statsMessage.getTotalRevenue() / 100.0); // 转换为元
            
            // 设置分类数据
            if (statsMessage.getCategoryStats() != null && !statsMessage.getCategoryStats().isEmpty()) {
                StringBuilder categories = new StringBuilder();
                for (StatsMessage.CategoryStat stat : statsMessage.getCategoryStats()) {
                    if (categories.length() > 0) {
                        categories.append(", ");
                    }
                    categories.append(stat.getType())
                            .append("(")
                            .append(stat.getOrders())
                            .append("单,")
                            .append(stat.getRevenue() / 100.0)
                            .append("元)");
                }
                miniMessage.setCategories(categories.toString());
            }
            
            // 设置排行榜
            if (statsMessage.getLeaderboard() != null && !statsMessage.getLeaderboard().isEmpty()) {
                miniMessage.setLeaderboard(String.join(", ", statsMessage.getLeaderboard()));
            }
            
            // 转换为JSON字符串
            String jsonMessage = objectMapper.writeValueAsString(miniMessage);
            log.info("发送微信小程序消息: {}", jsonMessage);
            
            // 发送到微信小程序专用主题
            messagingTemplate.convertAndSend(MINI_PROGRAM_TOPIC, miniMessage);
        } catch (JsonProcessingException e) {
            log.error("转换微信小程序消息失败: {}", e.getMessage());
        }
    }
    
    /**
     * 发送测试消息
     */
    public void sendTestMessage() {
        try {
            // 普通测试消息
            String testMessage = "WebSocket测试消息 - " + System.currentTimeMillis();
            log.info("发送测试消息: {}", testMessage);
            messagingTemplate.convertAndSend(STATS_TOPIC, testMessage);
            
            // 微信小程序测试消息
            MiniProgramMessage miniMessage = new MiniProgramMessage();
            miniMessage.setType("test");
            miniMessage.setMessage("小程序测试消息 - " + System.currentTimeMillis());
            messagingTemplate.convertAndSend(MINI_PROGRAM_TOPIC, miniMessage);
        } catch (Exception e) {
            log.error("发送测试消息失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 微信小程序消息格式
     * 简化的消息格式，适合小程序处理
     */
    public static class MiniProgramMessage {
        private String type;
        private String message;
        private Long totalOrders;
        private Double totalRevenue;
        private String categories;
        private String leaderboard;
        private Long timestamp = System.currentTimeMillis();
        
        // Getters and Setters
        public String getType() { return type; }
        public void setType(String type) { this.type = type; }
        
        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }
        
        public Long getTotalOrders() { return totalOrders; }
        public void setTotalOrders(Long totalOrders) { this.totalOrders = totalOrders; }
        
        public Double getTotalRevenue() { return totalRevenue; }
        public void setTotalRevenue(Double totalRevenue) { this.totalRevenue = totalRevenue; }
        
        public String getCategories() { return categories; }
        public void setCategories(String categories) { this.categories = categories; }
        
        public String getLeaderboard() { return leaderboard; }
        public void setLeaderboard(String leaderboard) { this.leaderboard = leaderboard; }
        
        public Long getTimestamp() { return timestamp; }
        public void setTimestamp(Long timestamp) { this.timestamp = timestamp; }
    }
} 